//
//  KeyedArchiverViewController.m
//  GCD
//
//  Created by fangyuan ding on 2020/8/12.
//  Copyright © 2020 fangyuan ding. All rights reserved.
//

#import "KeyedArchiverViewController.h"
#import "Person.h"
@interface KeyedArchiverViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameArchiverTextField;
@property (weak, nonatomic) IBOutlet UITextField *ageArchiverTextField;
@property (weak, nonatomic) IBOutlet UITextField *nameUnArchiverTextField;
@property (weak, nonatomic) IBOutlet UITextField *ageUnArchiverTextField;
@property (strong,nonatomic)NSString *documentsPath;
@property (strong,nonatomic)Person *person;

@end

@implementation KeyedArchiverViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.nameUnArchiverTextField.delegate = self;
    self.ageUnArchiverTextField.delegate = self;
    self.nameArchiverTextField.delegate = self;
    self.ageArchiverTextField.delegate = self;
    self.person = [[Person alloc]init];
    [[NSNotificationCenter defaultCenter]addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        [self Archiver:nil];
        NSLog(@"archiver");
    }];
    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}
- (NSString *)documentsPath{
    if(!_documentsPath){
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
        if(paths.count > 0){
            _documentsPath = paths.firstObject;
            //如果目录不存在，则创建目录
            if(![[NSFileManager defaultManager]fileExistsAtPath:_documentsPath]){
                NSError *error;
                //创建目录
                if(![[NSFileManager defaultManager]createDirectoryAtPath:_documentsPath withIntermediateDirectories:YES attributes:nil error:&error]){
                    NSLog(@"Failed to create directory. error:%@",error);
                }
            }
        }
    }
    return _documentsPath;
}
- (IBAction)Archiver:(id)sender {
    //把当前文本框内文件传送给person
    [self.person setName:self.nameArchiverTextField.text age:[self.ageArchiverTextField.text integerValue]];
    NSMutableData *mutableData = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mutableData];
    [archiver encodeObject:self.person forKey:@"person"];
    [archiver finishEncoding];
    //把归档写入Library/Application support/Data目录
    NSString *filePath = [self.documentsPath stringByAppendingPathComponent:@"Data"];
    if(![mutableData writeToFile:filePath atomically:YES]){
        NSLog(@"Failed to write file to filePath");
    }
}

- (IBAction)unArchiver:(id)sender {
    NSString *filePath = [self.documentsPath stringByAppendingPathComponent:@"Data"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    self.person = [unarchiver decodeObjectForKey:@"person"];
    [unarchiver finishDecoding];
    //读取到的内容显示到对应的文本框
    self.nameUnArchiverTextField.text = self.person.name;
    self.ageUnArchiverTextField.text = [@(self.person.age) stringValue];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
@end
